//
//  SetPhotoViewController.m
//  Arts1
//
//  Created by apple on 15/9/20.
//  Copyright © 2015年 Arts1. All rights reserved.
//

#import "SetPhotoViewController.h"
#import "LabelsCollectionViewCell.h"
#import "LabelsModel.h"
#import "LabelsHeaderView.h"
#import "LabelsViewController.h"
#import "AllHeader.h"

#define kURL @"http://arts1.dlab.com.cn/app/addphoto"

#define kBorderColor [UIColor colorWithRed:219/255.0 green:217/255.0 blue:216/255.0 alpha:1]

@interface SetPhotoViewController ()<UICollectionViewDelegateFlowLayout,UICollectionViewDelegate,UICollectionViewDataSource,UITextViewDelegate>

//标签视图
@property (nonatomic ,strong) UICollectionView *collectionLabel;
//接收plist读取的数据
@property (nonatomic ,strong) NSArray *dataArray;
//存储model模型
@property (nonatomic ,strong) NSMutableArray *array;
//下拉框右边的图标
@property (nonatomic ,strong) UIButton *icon;
//记录选择多少标签
@property (nonatomic ,assign) int count;
//存储选中的标签内容
@property (nonatomic ,strong) NSMutableArray *countLabelArray;
//获取所有的标签
@property (nonatomic ,strong) NSMutableString *strLabel;
//显示选择的标签视图
@property (nonatomic ,strong) LabelsViewController *collectionShowView;

@property (nonatomic ,strong) UILabel *placeholder;

@end

@implementation SetPhotoViewController

//存储model模型
- (NSMutableArray *)array
{
    if (_array == nil)
    {
        self.array = [NSMutableArray array];
    }
    return _array;
}
//存储选中的标签内容
- (NSMutableArray *)countLabelArray
{
    if (_countLabelArray == nil)
    {
        self.countLabelArray = [NSMutableArray arrayWithCapacity:5];
    }
    return _countLabelArray;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    //记录选择的标签个数
    _count = 0;
    
    //读取plist文件数据
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Labels" ofType:@"plist"];
    
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:path];
    
    _dataArray = dic[@"data"];
    
    for (NSDictionary *dic in _dataArray)
    {
        LabelsModel *model = [[LabelsModel alloc] init];
        [model setValuesForKeysWithDictionary:dic];
        [self.array addObject:model];
    }
    [self.collectionLabel reloadData];
    //创建视图
    [self creactView];
}
//创建视图
- (void)creactView
{
    
    //图片后面的覆盖的视图
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - 106 * WIDTH, 159 * HEIGHT)];
   
    view.layer.masksToBounds = YES;
    view.userInteractionEnabled = NO;
    [UIView viewRediusForLeftAndReightOfTop:view withRedius:10];
    
    //图片视图
    _image = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - 106 * WIDTH, 159 * HEIGHT)];
    [_image setContentMode:(UIViewContentModeScaleAspectFill)];
    _image.userInteractionEnabled = NO;
    [view addSubview:_image];
     [self.view addSubview:view];
    
    
    //下拉视图
    _bottomView = [[UIView alloc] initWithFrame:CGRectMake(10, _image.bottom + 10, _image.width - 20, 30)];
    _bottomView.layer.borderColor = kBorderColor.CGColor;
    _bottomView.layer.borderWidth = 0.5;
    _bottomView.layer.cornerRadius = 4;
    _bottomView.clipsToBounds = YES;
    _bottomView.layer.masksToBounds = YES;
    [self.view addSubview:_bottomView];
    
    
    [self creactLabelsShowView];
    
    //设置发布内容的编辑框
    _textView = [[UITextView alloc] initWithFrame:CGRectMake(10, _bottomView.bottom + 10, _image.width - 20, 85)];
    _textView.layer.borderColor = kBorderColor.CGColor;
    _textView.layer.borderWidth = 0.5;
    _textView.layer.cornerRadius = 4;
    _textView.clipsToBounds = YES;
    _textView.layer.masksToBounds = YES;
    _textView.delegate = self;
    _textView.font = [UIFont systemFontOfSize:11];
    [self.view addSubview:_textView];
    
    
    //自定义textView上面的类似textFile上的placeholder
    _placeholder = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, _textView.width, 30)];
    _placeholder.textAlignment = NSTextAlignmentLeft;
    _placeholder.font = [UIFont systemFontOfSize:11];
    _placeholder.textColor = [UIColor grayColor];
    _placeholder.text = @"刚刚临摹的一张图片，欢迎吐槽...";
    [_textView addSubview:_placeholder];
    
    //发布按钮
    _btnCommint = [UIButton buttonWithType:UIButtonTypeCustom];
    _btnCommint.layer.cornerRadius = 4;
    _btnCommint.clipsToBounds = YES;
    _btnCommint.layer.masksToBounds = YES;
    _btnCommint.backgroundColor = kCustomColor(40, 40, 40, 1);
    _btnCommint.layer.borderColor = kCustomColor(40, 40, 40, 1).CGColor;
    [_btnCommint setTintColor:kCustomColor(40, 40, 40, 1)];
    [_btnCommint setTitle:@"发布" forState:(UIControlStateNormal)];
    [_btnCommint addTarget:self action:@selector(commintData:) forControlEvents:(UIControlEventTouchUpInside)];
    
    _btnCommint.frame = CGRectMake(10, _textView.bottom + 10, _image.width - 20, 30);
    [self.view addSubview:_btnCommint];
    
    //调用标签视图
    [self creactLabelsView];
    
    
    //下拉控件
    _bottomButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _bottomButton.frame = CGRectMake(0, 0, _bottomView.width, 30);
    _bottomButton.layer.borderColor = kBorderColor.CGColor;
    _bottomButton.layer.borderWidth = 0.5;
    _bottomButton.layer.cornerRadius = 4;
    _bottomButton.clipsToBounds = YES;
    _bottomButton.layer.masksToBounds = YES;
    [_bottomButton addTarget:self action:@selector(showLabels:) forControlEvents:(UIControlEventTouchUpInside)];
    [_bottomView addSubview:_bottomButton];
    
    //下拉框图标
    _icon = [UIButton buttonWithType:UIButtonTypeCustom];
    _icon.frame = CGRectMake(_bottomView.right - 40, 0, 30, _bottomView.height);
    
    [_icon setBackgroundImage:[UIImage imageNamed:@"Triangle"] forState:UIControlStateNormal];
    [_icon addTarget:self action:@selector(showLabels:) forControlEvents:(UIControlEventTouchUpInside)];

    [_bottomView addSubview:_icon];
}

//发布内容的编辑框开始编辑
- (void)textViewDidChange:(UITextView *)textView
{
    if (textView.text.length == 0)
    {
        _placeholder.text = @"刚刚临摹的一张图片，欢迎吐槽...";
    }
    else
    {
        _placeholder.text = @"";
    }
}

/**
 *  发布数据
 */
- (void)commintData:(UIButton *)button
{
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    manage.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"multipart/form-data"];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    //压缩图片
    NSData *imageData = UIImageJPEGRepresentation(_image.image, 1.0);
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString *str = [formatter stringFromDate:[NSDate date]];
    NSString *fileName = [NSString stringWithFormat:@"%@.png",str];
    
    NSDictionary *dic = [[NSUserDefaults standardUserDefaults] objectForKey:@"dataForKeyAndUid"];
    
    NSString *uid = dic[@"data"][@"uid"];
    
    NSString *key = dic[@"data"][@"key"];
    
    NSMutableDictionary *pardic = [NSMutableDictionary dictionary];
    
    
    if (uid && key)
    {
        [pardic setValue:uid forKey:@"uid"];
        [pardic setValue:key forKey:@"key"];
        [pardic setValue:@"1" forKey:@"status"];
    }
    if (_textView.text.length != 0)
    {
        [pardic setValue:_textView.text forKey:@"info"];
    }
    
    //获取标签的参数值
    if (self.countLabelArray.count != 0)
    {
        NSMutableString *str = [NSMutableString string];
        
        for (int i = 0; i < self.countLabelArray.count; i++)
        {
            if (i == 0)
            {
                str = [_countLabelArray[0] mutableCopy];
            }
            else
            {
                [str appendString:_countLabelArray[i]];
            }
        }
        [pardic setValue:str forKey:@"tags"];
    }
    
    [manage POST:kURL parameters:pardic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData)
    {
        if (imageData)
        {
            //设置图片的格式
            [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/png"];
        }
        
    } success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        
        //移除视图
        if (_removeView)
        {
            _removeView();
        }
        
        
        NSLog(@"--------------%@",responseObject);
        
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        
    }];
}


//添加标签视图
- (void)creactLabelsView
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumInteritemSpacing = 5;
    layout.minimumLineSpacing = 10;
    layout.itemSize = CGSizeMake(40, 19);
    
    _collectionLabel = [[UICollectionView alloc] initWithFrame:CGRectMake(10, _bottomView.bottom, _bottomView.width, 0) collectionViewLayout:layout];
    _collectionLabel.delegate = self;
    _collectionLabel.dataSource = self;
    _collectionLabel.layer.borderWidth = 0.5;
    _collectionLabel.layer.cornerRadius = 4;
    _collectionLabel.layer.borderColor = kCustomColor(150, 150,150, 0.5).CGColor;
    _collectionLabel.backgroundColor = [UIColor whiteColor];
    
    //注册类
    [_collectionLabel registerClass:[LabelsCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    [_collectionLabel registerClass:[LabelsHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    
    [self.view addSubview:self.collectionLabel];
    
}
//创建显示标签元素的视图
- (void)creactLabelsShowView
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumInteritemSpacing = 2;
    layout.itemSize = CGSizeMake(30, 19);
    layout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
    
    _collectionShowView = [[LabelsViewController alloc] initWithCollectionViewLayout:layout];
    [self.bottomView addSubview:_collectionShowView.view];
    [_collectionShowView.view bringSubviewToFront:_bottomView];
    _collectionShowView.view.frame = CGRectMake(0, 0, _image.width - 20,30);
    _collectionShowView.collectionView.backgroundColor = [UIColor whiteColor];
    _collectionShowView.view.layer.borderColor = kCustomColor(150, 150,150, 0.5).CGColor;
}

#pragma mark - 下拉添加标签,根据标签视图的显示状态改变是否显示和隐藏
//下拉添加标签,根据标签视图的显示状态改变是否显示和隐藏
- (void)showLabels:(UIButton *)changePage
{
    //如果弹出视图是负的，就是隐藏的时候
    if (_collectionLabel.frame.size.height == 0)
    {
        [UIView animateWithDuration:0.5 animations:^{
            
            //先获取弹出视图的大小
            CGRect rect = _collectionLabel.frame;
            //改变弹出视图的大小的距离y的值.(弹出)
            rect.size.height = 95 * HEIGHT;
            //重新给这个视图新的位置
            _collectionLabel.frame = rect;
            //按钮的位置旋转一180度 CGAffineTransformMakeRotation（旋转）
            _icon.transform = CGAffineTransformRotate(_icon.transform, M_PI);
        }];
    }
    else
    {
        [UIView animateWithDuration:0.5 animations:^{
            CGRect rect = _collectionLabel.frame;
            rect.size.height = 0;
            _collectionLabel.frame = rect;
            _icon.transform = CGAffineTransformRotate(_icon.transform, -M_PI);
        } completion:^(BOOL finished) {
        }];
    }
}

//设置多少分区
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (_array.count == 0)
    {
        return 0;
    }
    return _array.count;
}

#pragma mark - 重绘cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    LabelsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];

    cell.layer.borderWidth = 0.5;
    cell.layer.borderColor = kCustomColor(150, 150, 150, 0.5).CGColor;
    cell.layer.cornerRadius = 2;
    LabelsModel *model = _array[indexPath.row];
    cell.model = model;
    return cell;
}

#pragma mark - 选择标签
//点击选中对应的cell
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    //给选中的标签赋值

    LabelsModel *model = _array[indexPath.row];

    [self countOfArrayData:model];
    
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    NSNotification *cation = [[NSNotification alloc] initWithName:@"setLabelData" object:model.labelName userInfo:nil];
    [center postNotification:cation];
    
    [_array replaceObjectAtIndex:indexPath.row withObject:model];
    
    [self.collectionLabel reloadData];
}

//记录选中的个数
- (void)countOfArrayData:(LabelsModel *)model
{
    BOOL isAdd = YES;
    int index = 0;
    
    for (NSString *string in self.countLabelArray)
    {
        if ([string isEqualToString:model.labelName])
        {
            isAdd = NO;
            index = (int)[self.countLabelArray indexOfObject:string];
        }
    }
    if (isAdd)
    {
        if (_countLabelArray.count < 5)
        {
            [self.countLabelArray addObject:model.labelName];
            model.isSelect = YES;
        }
    }
    else
    {
        [self.countLabelArray removeObjectAtIndex:index];
        model.isSelect = NO;
    }
}

#pragma mark - 设置上下左右的间距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10, 5, 10, 5);
}

#pragma mark - 设置标签头部视图大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    CGSize size = {self.view.bounds.size.width,20};
    return size;
}

#pragma mark - 设置标签头部视图
- (UICollectionReusableView *) collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    LabelsHeaderView *reusableview = nil;
    
    if (kind == UICollectionElementKindSectionHeader)
    {
        reusableview = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
        [reusableview setLabelText:@"请选择少于5个标签"];
    }
    
    reusableview.backgroundColor = kCustomColor(240, 240, 240, 1.0);
    return reusableview;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}


@end
